package com.yide.myworld.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yide.myworld.domain.ChoosePayDto;
import com.yide.myworld.domain.CommonAppPayDto;
import com.yide.myworld.domain.VerifyUserDto;
import com.yide.myworld.exception.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 通用支付请求工具类
 *
 * @auth: yifan
 * @date: 2023/1/9 4:47 PM
 * @ClassName: PaymentUtil
 * @Description:Payment Request
 */
@Service
public class PaymentService {
    @Value("${tianmcloud.finance.url:http://test-financial.tianmcloud.top}")
    private String url;
    @Value("${tianmcloud.finance.appKey:63bbd21589cfb3784}")
    private String appKey;
    @Value("${tianmcloud.finance.appSecret:0e8b0054044fe66d7a76317c8b543762a11e783f10c7ecdaaff5c57bcef71c9b}")
    private String appSecret;
    @Value("${tianmcloud.finance.returnUrl:https://h5api.qushengfun.com/h5api/water/#/pages/pay/index}")
    private String returnUrl;


    private String common(String url, List<NameValuePair> nvps) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            List<NameValuePair> signs = new ArrayList<>();
            signs.addAll(nvps);
            signs.add(new BasicNameValuePair("appkey", appKey));
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            signs.add(new BasicNameValuePair("timestamp", timestamp));
            signs.sort(Comparator.comparing(NameValuePair::getName, Comparator.reverseOrder()));
            StringBuffer sb = new StringBuffer();
            JSONObject jsonObject = new JSONObject();
            for (NameValuePair sign : signs) {
                sb.append(sign.getName() + sign.getValue());
            }
            for (NameValuePair nvp : nvps) {
                jsonObject.put(nvp.getName(), nvp.getValue());
            }
            sb.append(appSecret);
            MD5 md5 = new MD5();
            String sign = md5.digestHex(sb.toString());
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            httpPost.addHeader("sign", sign);
            httpPost.addHeader("appkey", appKey);
            httpPost.addHeader("timestamp", timestamp);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            //设置请求的参数

            StringEntity stringEntity = new StringEntity(jsonObject.toString(), "utf-8");
            stringEntity.setContentType("text/json");

            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        } finally {
            if (null != httpPost) {
                httpPost.releaseConnection();
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 选择支付方式
     *
     * @param dto
     * @return
     */
    public String choosePay(ChoosePayDto dto) {
        String url = this.url + "/pay/choose/pay";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        /** 用户ID */
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        /** 用户呢称 */
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        /** 用户code码 */
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        /** 支付金额(分) */
        nvps.add(new BasicNameValuePair("money", dto.getMoney()));
        /** 订单号 */
        nvps.add(new BasicNameValuePair("order_sn", dto.getOrder_sn()));
        /** 订单创建时间 2020-11-11 11:11:11 */
        nvps.add(new BasicNameValuePair("order_create_time", dto.getOrder_create_time()));
        /** 商户类型: 1-支付宝 ; 2-微信; 3-苹果内购 */
        nvps.add(new BasicNameValuePair("merchant_type", dto.getMerchant_type()));
        /** 支付来源: 1-app; 2-h5 */
        nvps.add(new BasicNameValuePair("created_from", dto.getCreated_from()));
        /** 标题 */
        nvps.add(new BasicNameValuePair("subject", dto.getSubject()));
        /** 支付渠道：0-未知;1-支付宝；2-微信 */
        nvps.add(new BasicNameValuePair("pay_type", dto.getPay_type()));

        return common(url, nvps);
    }

    /**
     * 微信
     *
     * @param dto
     * @return
     */
    public String wechatAppPay(CommonAppPayDto dto) {
        String url = this.url + "/pay/wx/app";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("money", dto.getMoney()));
        nvps.add(new BasicNameValuePair("order_sn", dto.getOrder_sn()));
        nvps.add(new BasicNameValuePair("subject", dto.getSubject()));
        nvps.add(new BasicNameValuePair("order_create_time", dto.getOrder_create_time()));

        if (StringUtils.isNotBlank(dto.getExpire_time())) {
            nvps.add(new BasicNameValuePair("expire_time", dto.getExpire_time()));
        }
        //请求网易云服务端
        return common(url, nvps);
    }

    public String wechatH5Pay(CommonAppPayDto dto) {
        String url = this.url + "/pay/wx/h5";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("money", dto.getMoney()));
        nvps.add(new BasicNameValuePair("order_sn", dto.getOrder_sn()));
        nvps.add(new BasicNameValuePair("subject", dto.getSubject()));
        nvps.add(new BasicNameValuePair("order_create_time", dto.getOrder_create_time()));
        nvps.add(new BasicNameValuePair("return_url", returnUrl));

        if (StringUtils.isNotBlank(dto.getExpire_time())) {
            nvps.add(new BasicNameValuePair("expire_time", dto.getExpire_time()));
        }
        //请求网易云服务端
        return common(url, nvps);
    }

    /**
     * 支付宝
     *
     * @param dto
     * @return
     */
    public String aliAppPay(CommonAppPayDto dto) {
        String url = this.url + "/pay/ali/app";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("money", dto.getMoney()));
        nvps.add(new BasicNameValuePair("order_sn", dto.getOrder_sn()));
        nvps.add(new BasicNameValuePair("subject", dto.getSubject()));
        nvps.add(new BasicNameValuePair("order_create_time", dto.getOrder_create_time()));

        if (StringUtils.isNotBlank(dto.getExpire_time())) {
            nvps.add(new BasicNameValuePair("expire_time", dto.getExpire_time()));
        }
        //请求网易云服务端
        return common(url, nvps);
    }

    public String aliH5Pay(CommonAppPayDto dto) {
        String url = this.url + "/pay/ali/h5";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("money", dto.getMoney()));
        nvps.add(new BasicNameValuePair("order_sn", dto.getOrder_sn()));
        nvps.add(new BasicNameValuePair("subject", dto.getSubject()));
        nvps.add(new BasicNameValuePair("order_create_time", dto.getOrder_create_time()));
        nvps.add(new BasicNameValuePair("return_url", returnUrl));

        if (StringUtils.isNotBlank(dto.getExpire_time())) {
            nvps.add(new BasicNameValuePair("expire_time", dto.getExpire_time()));
        }
        //请求网易云服务端
        return common(url, nvps);
    }


    public String verifyUser(VerifyUserDto dto) {
        String url = this.url + "/verify/user";
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("truename", dto.getTruename()));
        nvps.add(new BasicNameValuePair("id_card", dto.getId_card()));
        nvps.add(new BasicNameValuePair("alipay_account", dto.getAlipay_account()));
        nvps.add(new BasicNameValuePair("mobile", dto.getMobile()));
        nvps.add(new BasicNameValuePair("user_id", dto.getUser_id()));
        nvps.add(new BasicNameValuePair("user_code", dto.getUser_code()));
        nvps.add(new BasicNameValuePair("nickname", dto.getNickname()));

        //请求网易云服务端
        return common(url, nvps);
    }

    public static void main(String[] args) {
        PaymentService paymentService = new PaymentService();

        VerifyUserDto dto = new VerifyUserDto();

        dto.setTruename("张三");
        dto.setId_card("412422211455666767");
        dto.setAlipay_account("15837589090");
        dto.setMobile("15837589090");
        dto.setUser_id("654321");
        dto.setUser_code("123456789");
        dto.setNickname("张三");


        String s = paymentService.verifyUser(dto);

        System.out.println("------------s--------" + s);


        JSONObject resultJSONObject = JSON.parseObject(s);
        System.out.println("---resultJSONObject---" + resultJSONObject);

        Object code = resultJSONObject.get("code");
        String dd = String.valueOf(code);

        System.out.println("---d----" + dd);

        Object data1 = resultJSONObject.get("data");
        System.out.println("--data1-----" + data1);

        JSONObject jsonObject = JSON.parseObject(String.valueOf(data1));
        Object status = jsonObject.get("status");
        System.out.println("--status----" + status);


        Object content1 = jsonObject.get("content");
        System.out.println("--content1---" + content1);

        Object appKeyId = jsonObject.get("app_key_id");
        System.out.println("--appKeyId--" + appKeyId);


    }


//    public static void main(String[] args) throws Exception {
//        PaymentService paymentUtil = new PaymentService();
//        ChoosePayDto choosePayDto = new ChoosePayDto();
//        choosePayDto.setUser_id("567187");
//        choosePayDto.setNickname("酱鸭哥");
//        choosePayDto.setUser_code("639a7e9c7ace9626be71c839");
//        choosePayDto.setMoney("10000");
//        choosePayDto.setOrder_sn("202301091829110000001");
//        choosePayDto.setOrder_create_time("2023-1-9 18:29:11");
//        choosePayDto.setMerchant_type("2");
//        choosePayDto.setCreated_from("1");
//        choosePayDto.setSubject("wechatPay");
//        choosePayDto.setPay_type("2");
//
//        String result = paymentUtil.choosePay(choosePayDto);
//        JSONObject resultJSONObject = JSON.parseObject(result);
//        System.out.println(result);
//        System.out.println(resultJSONObject.get("code"));
//        System.out.println(resultJSONObject.get("message"));
//
//        CommonAppPayDto commonAppPayDto = new CommonAppPayDto();
//        commonAppPayDto.setUser_id("567187");
//        commonAppPayDto.setNickname("酱鸭哥");
//        commonAppPayDto.setUser_code("639a7e9c7ace9626be71c839");
//        commonAppPayDto.setMoney("10000");
//        commonAppPayDto.setOrder_sn("202301091829110000001");
//        commonAppPayDto.setSubject("wechatPay");
//        commonAppPayDto.setOrder_create_time("2023-1-9 18:29:11");
//
//        result = paymentUtil.wechatAppPay(commonAppPayDto);
//        resultJSONObject = JSON.parseObject(result);
//        System.out.println(result);
//        System.out.println(resultJSONObject.get("code"));
//        System.out.println(resultJSONObject.get("message"));
//
//    }

}